Skip to main content

Mocha

In this tutorial, we'll start with a JavaScript NodeJS project that has an existing Mocha test suite, and we'll add JUnit XML as an additional output format for the test suite. JUnit XML contains data such as passed and failed tests, suitenames, test files, filenames, test cases, and error messages helpful for debugging. In each step in this doc, we'll show the Git diff for the change that we're making.

  1. Add mocha-junit-reporter and mocha-multi-reporters as development dependencies (no need for custom reporters!).

    npm install --save-dev mocha-junit-reporter mocha-multi-reporters

    Verify that your package.json file includes these new dependencies:

       "author": "Richard Hendricks",
    "license": "MIT",
    "devDependencies": {
    - "mocha": "^9.1.1"
    + "mocha": "^9.1.1",
    + "mocha-junit-reporter": "^2.0.0",
    + "mocha-multi-reporters": "^1.5.1"
    }
    }
  2. Create a mocha-reporter-config.json file and configure it to enable the spec reporter (which is the default Mocha reporter) and the mocha-junit-reporter as a parameter after the spec default reporter.

    +{
    + "reporterEnabled": "spec, mocha-junit-reporter"
    +}
  3. Update your CI workflow to use mocha-multi-reporters as the test reporter plugin. Here we update npm test to use the new reporter configuration that we set up above, with inline reporter-options output.

       jobs:

    - run: npm ci
    - - run: npm test
    + - run: npm test -- --reporter mocha-multi-reporters --reporter-options configFile=mocha-reporter-config.json

    This example project uses Github Actions for CI, so we're updating our CI script in the .github/workflows/ directory. If you're using a different CI service, apply the same change wherever your CI script is defined (e.g., .circleci/config.yml for CircleCI, etc.).

  4. By default, mocha-junit-reporter exports the report to a file named test-results.xml at the root of your project. Add that to your .gitignore file so that it doesn't accidentally get checked into the repository.

    /node_modules
    +/test-results.xml
  5. Commit these changes to your repository using the git command line tool.

    git commit -am "Update CI to generate JUnit XML for test results"

    The final result of these changes should resemble commit 30e6cef in the buildpulse-example-mocha repository - or view the README for setup repository instructions.

    When you run tests or your test script, you should now see generated junit xml files (with tests failed and passed) in your test reports directory for MochaJS - the first step in detecting flaky tests.